import { useState, useRef, useMemo, useContext } from 'react';
import { MySdkStoreContext } from '../../context';

import './style.scss';

export default function(props) {
  const audioRef = useRef(null);
  const { url = '', duration } = props.msgContent;
  const mySdkStore = useContext(MySdkStoreContext);
  const { mockConfig: { userId: myUserId } } = mySdkStore;
  const [isPlaying, setIsPlaying] = useState(false);
  const audio = useMemo(() => new Audio(url), [url]);

  const togglePlay = (e) => {
    if (!isPlaying) {
      audio.play();
      setIsPlaying(true);
    } else {
      audio.pause();
      setIsPlaying(false);
    }

    e.stopPropagation();
  }

  audio.onended = () => {
    setIsPlaying(false);
  }

  return <div className={`voiceComponent ${props.from?.userId === myUserId ? 'rightVoice' : 'leftVoice'}`} style={{ width: '30vw' }}>
    <span className={isPlaying ? 'playingIcon' : 'pauseIcon'} onClick={togglePlay} />
    { Math.ceil(duration) }"
    <audio src={url} ref={audioRef} />
  </div>;
}